const File = require("../models/fileModel");
const mongoose = require("mongoose");

const path = require("path");
const fs = require("fs");

//上传图片
exports.singleFileUpload = async (req, res, next) => {
  try {
    // console.log("hhh", req);
    // console.log("经过文件服务器的文件", req.file);
    const newFile = await File.create({
      fileName: req.file.filename,
      filePath: "public/" + req.file.filename,
      fileType: req.file.mimetype,
    });
    res.status(201).json({
      status: "success",
      message: newFile,
    });
  } catch (error) {
    res.status(400).send(error);
  }
};

//批量上传图片
exports.multiFileUpload = async (req, res, next) => {
  try {
    console.log("批量上传图片---");
    let files = [];
    for (let i = 0; i < req.files.length; i++) {
      files.push({
        fileName: req.files[i].filename,
        filePath: "public/" + req.files[i].filename,
        fileType: req.files[i].mimetype,
      });
    }
    console.log("files", files);
    let fileGroup = await File.insertMany(files);
    console.log("插入数据库后files", fileGroup);
    res.status(201).json({
      status: "success",
      message: fileGroup,
    });
    console.log("批量上传图片成功-----");
  } catch (error) {
    console.log("批量上传图片失败---");
    res.status(400).send(error);
  }
};

const remove = (filename) => {
  return new Promise((resolve, reject) => {
    fs.unlink(path.resolve("./public/" + filename), (err) => {
      if (err) {
        reject(console.log(err));
      }
      resolve(console.log("删除图片成功"));
    });
  });
};

//删除图片
exports.singleDelete = async (req, res, next) => {
  try {
    // console.log("开始删除", req.params);
    const id = mongoose.Types.ObjectId(req.params);
    // console.log("trytry", id);
    const data = await File.findOne({ _id: id });
    await remove(data.fileName);
    const result = await File.deleteOne({ _id: id });
    res.status(200).json({
      status: "success",
      message: result,
    });
  } catch (error) {
    console.log("删除图片出错了", error);
    res.status(400).send(error);
  }
};

//批量删除
exports.multiDelete = async (req, res, next) => {
  try {
    console.log("开始批量删除图片-----");
    let idGroup = req.body.map((id) => mongoose.Types.ObjectId(id));

    for (let i = 0; i < idGroup.length; i++) {
      const data = await File.findOne({ _id: idGroup[i] });
      await remove(data.fileName);
    }
    await File.deleteMany({ _id: { $in: idGroup } });
    console.log("批量删除图片结束-----");
    res.status(200).json({
      status: true,
      message: "批量删除成功",
    });
  } catch (err) {
    res.status(400).send(err);
  }
};

exports.getAllFiles = async (req, res, next) => {
  try {
    const files = await File.find();
    res.status(201).json({
      status: "success",
      message: files,
    });
  } catch (error) {
    res.status(400).send(error.message);
  }
};

exports.editFiles = async (req, res, next) => {
  try {
    //先增加新图片
    console.log("开始修改图片-------");
    let files = [];
    for (let i = 0; i < req.files.length; i++) {
      files.push({
        fileName: req.files[i].filename,
        filePath: "public/" + req.files[i].filename,
        fileType: req.files[i].mimetype,
      });
    }
    let fileGroup = await File.insertMany(files);
    // console.log("插入数据库后files", fileGroup);

    //再保留需保留图片
    let originFiles = [];
    // console.log("需保留图片", req.body.origin);
    if (req.body.origin !== undefined) {
      let originGroup = req.body.origin.map((id) =>
        mongoose.Types.ObjectId(id)
      );
      for (let i = 0; i < originGroup.length; i++) {
        const data = await File.findOne({ _id: originGroup[i] });
        originFiles.push(data);
      }
    }

    let finalFiles = originFiles.concat(fileGroup);
    // console.log("新增和保留后", finalFiles);

    //再删除需删除图片
    // console.log("待删除图片---", req.body.idGroup);
    if (req.body.idGroup !== undefined) {
      let idGroup = req.body.idGroup.map((id) => mongoose.Types.ObjectId(id));
      for (let i = 0; i < idGroup.length; i++) {
        const data = await File.findOne({ _id: idGroup[i] });
        await remove(data.fileName);
      }
      await File.deleteMany({ _id: { $in: idGroup } });
    }
    console.log("修改图片成功--------");
    res.status(201).json({
      status: "success",
      message: finalFiles,
    });
  } catch (error) {
    console.log("修改图片失败-----", error);
    res.status(400).send(error);
  }
};
